package org.example.component;

import com.alibaba.druid.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.mapper.DUserMapper;
import org.example.pojo.DUser;
import org.example.utils.JwtHelper;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private DUserMapper dUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        //判断是否有token
        if (StringUtils.isEmpty(token) || jwtHelper.isExpiration(token)){
            // 如果token无效，返回响应
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token");
            //拦截
            return false;
        }else{
            //解析token
            int userId = jwtHelper.getUserId(token).intValue();

            DUser userSelect = new DUser();
            userSelect.setUid(userId);
            DUser user = dUserMapper.selectByUid(userSelect);

            //判断用户是否被禁用
            if(user.getUserStatus() == 0){
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "该用户已经被禁用");
                return false;
            }
            //放行
            return true;
        }
    }
}